package com.ruoyi.file.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Author：汤小洋
 * Date：2024-11-08 10:50
 * Description：<描述>
 */
@Service
public class OssPolicyServiceImpl implements OssPolicyService {

    @Resource
    private OSS ossClient;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;

    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;

    @Override
    public Map<String, String> policy() throws UnsupportedEncodingException {
        String host = "https://"+bucket+"."+endpoint;
        String dir = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now());
        long expireEndTime = System.currentTimeMillis() + 30 * 1000; // 30秒后过期

        // 上传策略
        PolicyConditions policyConds = new PolicyConditions();
        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000); // 设置上传文件的大小限制
        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir); // 设置上传文件的文件夹
        String postPolicy = ossClient.generatePostPolicy(new Date(expireEndTime), policyConds); // 生成策略
        String encodedPolicy = BinaryUtil.toBase64String(postPolicy.getBytes("utf-8")); // 对策略进行base64编码

        // 签名
        String postSignature = ossClient.calculatePostSignature(postPolicy);

        Map<String, String> map = new LinkedHashMap<>();
        map.put("host", host); // 上传文件的host
        map.put("dir", dir); // 上传文件的文件夹
        map.put("expire", String.valueOf(expireEndTime / 1000)); // 上传文件的过期时间
        map.put("accessId", accessId); // accessId
        map.put("policy", encodedPolicy); // 上传策略
        map.put("signature", postSignature); // 签名
        return map;
    }
}